import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    redirect: '/system/user/userList',
    component: () => import('@/views/Main.vue'),
    children:[
      {
        path: '/system/user/userList',
        name: 'userList',
        meta:{
          one:"系统管理",
          two:"用户管理",
        },
        component: () => import('@/views/system/user/userList.vue')
      },
      {
        path: '/system/role/roleList',
        name: 'roleList',
        meta:{
          one:"系统管理",
          two:"角色管理",
        },
        component: () => import('@/views/system/role/roleList.vue')
      },
      {
        path: '/system/menu/menuList',
        name: 'menuList',
        meta:{
          one:"系统管理",
          two:"菜单管理",
        },
        component: () => import('@/views/system/menu/menuList.vue')
      },
      {
        path:"/shop/banner/bannerList",
        name:"bannerList",
        meta:{
          one:"商城管理",
          two:"banner管理",
        },
        component:()=>import("@/views/shop/banner/bannerList.vue")
      },
      {
        path:"/shop/goods/goodsList",
        name:"goodsList",
        meta:{
          one:"商城管理",
          two:"商品管理",
        },
        component:()=>import("@/views/shop/goods/goodsList.vue")
      },
      {
        path:"/shop/category/categoryList",
        name:"categoryList",
        meta:{
          one:"商城管理",
          two:"商品分类管理",
        },
        component:()=>import("@/views/shop/category/categoryList.vue")
      },
      {
        path:"/shop/order/orderList",
        name:"orderList",
        meta:{
          one:"商城管理",
          two:"订单管理",
        },
        component:()=>import("@/views/shop/order/orderList.vue")
      },
      {
        path:"/shop/cart/cartList",
        name:"cartList",
        meta:{
          one:"商城管理",
          two:"购物车管理",
        },
        component:()=>import("@/views/shop/cart/cartList.vue")
      },
    ]

  }
]
const router = new VueRouter({
  routes
})// 全局前置守卫，在路由跳转前进行拦截
router.beforeEach((to, from, next) => {
    try {
        // 从本地存储中获取token
        const token = localStorage.getItem('token');

        // 如果没有token，说明用户未登录
        if (!token) {
            // 如果目标路由是登录页，允许跳转
            if (to.path === '/login') {
                return next();
            } else {
                // 否则重定向到登录页
                return next('/login');
            }
        }

        // 如果已经登录，且目标路由是登录页
        if (to.path === '/login') {
            // 重定向到上一个路由
            return next(from);
        }

        // 其他情况允许跳转
        return next();
    } catch (error) {
        // 处理本地存储操作可能出现的异常
        console.error('本地存储操作出错:', error);
        // 出现异常时重定向到登录页
        next('/login');
    }
});


export default router
